package me.sensen;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

import javax.print.PrintService;
import java.awt.print.PrinterJob;
import java.io.File;

/**
 * @author Sensen
 */
public class Services {

    public static PDDocument printPdf(String pdfPath, String printerName) {
        try {
            File file = new File(pdfPath);
            PDDocument document = PDDocument.load(file);
            PrinterJob job = getPrintServiceByName(printerName);
            setPageStyle(document, job);
            // 开始打印
            job.print();
            return document;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static PrinterJob getPrintServiceByName(String printerName) throws Exception{
        PrinterJob job = PrinterJob.getPrinterJob();
        // 遍历查询打印机名称
        boolean flag = false;
        for (PrintService ps : PrinterJob.lookupPrintServices()) {
            String psName = ps.toString();
            if (psName.contains(printerName)) {
                flag = true;
                job.setPrintService(ps);
                break;
            }
        }
        if(!flag){
            throw new RuntimeException("打印失败，未找到名称为" + printerName + "的打印机，请检查。");
        }
        return job;
    }

    private static void setPageStyle(PDDocument document, PrinterJob job) {
        job.setPageable(new PDFPageable(document));
    }

}